﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla;
using Csla.Data;

namespace Kiosk.Library
{
    partial class SlideReadOnlyList
    {
        public static SlideReadOnlyList GetSlidesByPresentationID(Guid presID)
        {
            return DataPortal.Fetch<SlideReadOnlyList>(new SingleCriteria<SlideReadOnlyList, Guid>(presID));
        }

        /// <summary>
        /// Returns the highest order for the slides in a presentation
        /// </summary>
        public static int GetHighestOrderForPresentation(Guid presID)
        {
            //TODO: do in a sproc
            int order = -1;
            if(SlideReadOnlyList.GetSlidesByPresentationID(presID).Count > 0)
            {
                order = SlideReadOnlyList.GetSlidesByPresentationID(presID).Max(s => s.Order);
            }
            return order;
        }

        private void DataPortal_Fetch(SingleCriteria<SlideReadOnlyList, Guid> criteria)
        {
            FetchAllByPresentation(criteria.Value);
        }

        private void FetchAllByPresentation(Guid presID)
        {
            RaiseListChangedEvents = false;
            using (var ctx = ContextManager<Kiosk.Data.KioskDataContext>.GetManager(Database.ConnectionString))
            {
                var data = from o in ctx.DataContext.Slide
                           where o.PresentationID == presID
                           orderby o.Order ascending
                           select o;
                IsReadOnly = false;
                foreach (var d in data)
                    this.Add(new SlideInfo(d.SlideID, d.PresentationID, d.Title, d.Location, d.Order));
                IsReadOnly = true;
            }
            RaiseListChangedEvents = true;
        }

        int _currentIndex = -1;
        /// <summary>
        /// Cycles through all the presentations one by one in order, only once
        /// </summary>
        /// <returns>
        /// The next slide, if no more slides it returns null
        /// </returns>
        public SlideInfo GetNextSlide()
        {
            _currentIndex++;
            if (_currentIndex >= this.Count)
            {
                return null;
            }
            else
            {
                return this[_currentIndex];
            }

        }
    }
}
